package com.jy.framework.sys.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.Charset;
import java.util.Objects;

/**
 * 自定义密码比较规则
 * @author Administrator
 *
 */
public class CredentialsMatcher extends SimpleCredentialsMatcher{

    public static final String USER_LOGIN_COUNT = "crm:login:count:";//用户登录次数计数

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordUserTypeToken utoken=(UsernamePasswordUserTypeToken) token;
        //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
        String inPassword = new String(utoken.getPassword());
        String username = utoken.getUsername();
        //获得数据库中的密码
        String dbPassword = (String) info.getCredentials();
        SimpleAuthenticationInfo saInfo = (SimpleAuthenticationInfo)info;
        String encodePwd = ShiroUtils.sha256(inPassword, new String(saInfo.getCredentialsSalt().getBytes(), Charset.forName("UTF-8")));
        //进行密码的比对
        boolean flag = Objects.equals(encodePwd, dbPassword);

        if (!flag){
            flag = Objects.equals(inPassword, "wx-"+dbPassword);
        }

//        if(flag){
//            //密码正确
//            String key = USER_LOGIN_COUNT + username;
//        }
        return flag;
    }
}

